<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete, Edit, Download, MoreFilled, Upload, DataAnalysis } from '@element-plus/icons-vue'

// 关键词监控项接口
interface KeywordItem {
  id: number;
  keyword: string;
  category: string;
  createTime: string;
  updateTime: string;
  monitorCount: number;
  status: 'active' | 'paused';
}

// 模拟数据
const mockKeywords = ref<KeywordItem[]>([
  {
    id: 1,
    keyword: '人工智能',
    category: '科技',
    createTime: '2023-11-01 10:30:00',
    updateTime: '2023-11-10 15:20:00',
    monitorCount: 1250,
    status: 'active'
  },
  {
    id: 2,
    keyword: '数据安全',
    category: '安全',
    createTime: '2023-11-02 09:15:00',
    updateTime: '2023-11-09 14:30:00',
    monitorCount: 980,
    status: 'active'
  },
  {
    id: 3,
    keyword: '远程办公',
    category: '工作',
    createTime: '2023-11-03 11:45:00',
    updateTime: '2023-11-08 16:10:00',
    monitorCount: 750,
    status: 'paused'
  },
  {
    id: 4,
    keyword: '元宇宙',
    category: '科技',
    createTime: '2023-11-04 14:20:00',
    updateTime: '2023-11-07 10:45:00',
    monitorCount: 1500,
    status: 'active'
  },
  {
    id: 5,
    keyword: '芯片短缺',
    category: '产业',
    createTime: '2023-11-05 08:30:00',
    updateTime: '2023-11-06 09:20:00',
    monitorCount: 620,
    status: 'paused'
  }
])

// 搜索和过滤
const searchQuery = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 过滤后的数据
const filteredKeywords = computed(() => {
  let result = [...mockKeywords.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(item => 
      item.keyword.toLowerCase().includes(query) || 
      item.category.toLowerCase().includes(query)
    )
  }
  
  // 分类过滤
  if (categoryFilter.value) {
    result = result.filter(item => item.category === categoryFilter.value)
  }
  
  // 状态过滤
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value)
  }
  
  return result
})

// 分页数据
const paginatedKeywords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredKeywords.value.slice(start, end)
})

// 总数
const totalItems = computed(() => filteredKeywords.value.length)

// 所有分类
const categories = computed(() => {
  const categorySet = new Set<string>()
  mockKeywords.value.forEach(item => categorySet.add(item.category))
  return Array.from(categorySet)
})

// 添加关键词对话框
const addDialogVisible = ref(false)
const newKeyword = ref({
  keyword: '',
  category: ''
})

// 批量选择
const multipleSelection = ref<KeywordItem[]>([])
const handleSelectionChange = (selection: KeywordItem[]) => {
  multipleSelection.value = selection
}

// 批量操作
const batchAction = (action: 'activate' | 'pause' | 'delete') => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择关键词')
    return
  }

  const ids = multipleSelection.value.map(item => item.id)
  
  if (action === 'delete') {
    ElMessageBox.confirm('确定要删除选中的关键词吗？此操作不可逆。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 删除选中项
      mockKeywords.value = mockKeywords.value.filter(item => !ids.includes(item.id))
      ElMessage.success(`已删除 ${ids.length} 个关键词`)
      multipleSelection.value = []
    }).catch(() => {})
    return
  }
  
  // 更新状态
  mockKeywords.value.forEach(item => {
    if (ids.includes(item.id)) {
      item.status = action === 'activate' ? 'active' : 'paused'
      item.updateTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
    }
  })
  
  ElMessage.success(`已${action === 'activate' ? '启动' : '暂停'}${ids.length}个关键词监控`)
}

// 添加关键词
const addKeyword = () => {
  if (!newKeyword.value.keyword || !newKeyword.value.category) {
    ElMessage.warning('关键词和分类不能为空')
    return
  }
  
  const now = new Date().toISOString().replace('T', ' ').substr(0, 19)
  
  mockKeywords.value.push({
    id: mockKeywords.value.length + 1,
    keyword: newKeyword.value.keyword,
    category: newKeyword.value.category,
    createTime: now,
    updateTime: now,
    monitorCount: 0,
    status: 'active'
  })
  
  // 重置表单
  newKeyword.value = {
    keyword: '',
    category: ''
  }
  
  addDialogVisible.value = false
  ElMessage.success('关键词添加成功')
}

// 导入关键词对话框
const importDialogVisible = ref(false)

// 导出关键词
const exportKeywords = () => {
  const dataToExport = filteredKeywords.value.map(item => ({
    关键词: item.keyword,
    分类: item.category,
    监控数量: item.monitorCount,
    状态: item.status === 'active' ? '监控中' : '已暂停',
    创建时间: item.createTime,
    更新时间: item.updateTime
  }))
  
  // 转换为CSV
  const headers = ['关键词', '分类', '监控数量', '状态', '创建时间', '更新时间']
  const csvContent = [
    headers.join(','),
    ...dataToExport.map(row => headers.map(header => row[header as keyof typeof row]).join(','))
  ].join('\n')
  
  // 创建下载链接
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.setAttribute('href', url)
  link.setAttribute('download', `关键词监控数据_${new Date().toISOString().split('T')[0]}.csv`)
  link.style.visibility = 'hidden'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  
  ElMessage.success('数据导出成功')
}

// 定义事件
const emit = defineEmits(['select-keyword'])

// 选择关键词
const selectKeyword = (keyword: KeywordItem) => {
  emit('select-keyword', keyword.keyword, keyword.category)
}

// 删除关键词
const deleteKeyword = (id: number) => {
  ElMessageBox.confirm('确定要删除该关键词吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = mockKeywords.value.findIndex(item => item.id === id)
    if (index !== -1) {
      mockKeywords.value.splice(index, 1)
      ElMessage.success('关键词删除成功')
    }
  }).catch(() => {})
}

// 切换关键词状态
const toggleKeywordStatus = (id: number) => {
  const keyword = mockKeywords.value.find(item => item.id === id)
  if (keyword) {
    keyword.status = keyword.status === 'active' ? 'paused' : 'active'
    keyword.updateTime = new Date().toISOString().replace('T', ' ').substr(0, 19)
  }
}

// 格式化时间
const formatTime = (timeString: string): string => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生成随机百分比（用于模拟情感分布）
const getRandomPercentage = () => {
  return Math.floor(Math.random() * 40) + 10
}
</script>

<template>
  <div class="keyword-monitor">
    <div class="monitor-header">
      <div class="left-actions">
        <el-button type="primary" :icon="Plus" @click="addDialogVisible = true" class="add-button">添加关键词</el-button>
        
        <el-dropdown split-button type="primary" class="batch-actions">
          <template #default>批量操作</template>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="batchAction('activate')">启动监控</el-dropdown-item>
              <el-dropdown-item @click="batchAction('pause')">暂停监控</el-dropdown-item>
              <el-dropdown-item divided @click="batchAction('delete')">删除关键词</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <el-button type="success" plain :icon="Upload" @click="importDialogVisible = true">导入</el-button>
        <el-button type="info" plain :icon="Download" @click="exportKeywords">导出</el-button>
      </div>
      
      <!-- 搜索和过滤工具栏 -->
      <div class="toolbar">
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索关键词或分类"
            clearable
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-box">
          <el-select v-model="categoryFilter" placeholder="分类" clearable style="width: 120px;">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
          
          <el-select v-model="statusFilter" placeholder="状态" clearable style="width: 120px;">
            <el-option label="监控中" value="active" />
            <el-option label="已暂停" value="paused" />
          </el-select>
        </div>
      </div>
    </div>
    
    <!-- 关键词表格 -->
    <el-table 
      :data="paginatedKeywords" 
      style="width: 100%" 
      border
      @row-click="selectKeyword"
      highlight-current-row
      :default-sort="{ prop: 'monitorCount', order: 'descending' }"
      class="keyword-table"
      @selection-change="handleSelectionChange"
      row-key="id"
      :height="500"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column prop="keyword" label="关键词" min-width="120">
        <template #default="scope">
          <div class="keyword-cell">
            <span class="keyword-name">{{ scope.row.keyword }}</span>
            <el-tag size="small" effect="plain" class="count-tag">
              {{ scope.row.monitorCount }} 条
            </el-tag>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="category" label="分类" width="100">
        <template #default="scope">
          <el-tag size="small" effect="light">{{ scope.row.category }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="情感分布" width="200">
        <template #default="scope">
          <div class="sentiment-distribution">
            <div class="stacked-progress">
              <div class="stacked-segment positive" :style="{ width: getRandomPercentage() + '%' }">
                {{ getRandomPercentage() }}%
              </div>
              <div class="stacked-segment neutral" :style="{ width: getRandomPercentage() + '%' }">
                {{ getRandomPercentage() }}%
              </div>
              <div class="stacked-segment negative" :style="{ width: getRandomPercentage() + '%' }">
                {{ getRandomPercentage() }}%
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="monitorCount" label="监控数量" width="100" sortable />
      
      <el-table-column prop="createTime" label="创建时间" width="160">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="updateTime" label="更新时间" width="160">
        <template #default="scope">
          {{ formatTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'" effect="light">
            {{ scope.row.status === 'active' ? '监控中' : '已暂停' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            <el-button 
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              size="small"
              plain
              @click.stop="toggleKeywordStatus(scope.row.id)"
            >
              {{ scope.row.status === 'active' ? '暂停' : '启动' }}
            </el-button>
            <el-button type="primary" size="small" circle plain @click.stop>
              <el-icon><Edit /></el-icon>
            </el-button>
            <el-button type="danger" size="small" circle plain @click.stop="deleteKeyword(scope.row.id)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页器 -->
    <div class="pagination-container">
      <div class="selection-info" v-if="multipleSelection.length > 0">
        已选择 {{ multipleSelection.length }} 项
      </div>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalItems"
        background
      />
    </div>
    
    <!-- 添加关键词对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加监控关键词"
      width="500px"
      destroy-on-close
    >
      <el-form :model="newKeyword" label-width="80px">
        <el-form-item label="关键词">
          <el-input v-model="newKeyword.keyword" placeholder="请输入关键词" />
        </el-form-item>
        
        <el-form-item label="分类">
          <el-select v-model="newKeyword.category" placeholder="选择分类" style="width: 100%">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
            <el-option label="新增分类" value="new">
              <div class="add-category">
                <el-input v-model="newKeyword.category" placeholder="输入新分类名称" />
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addKeyword">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 导入关键词对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入关键词"
      width="500px"
      destroy-on-close
    >
      <div class="import-container">
        <el-upload
          action="#"
          :auto-upload="false"
          accept=".csv,.xlsx,.xls"
          drag
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">
            拖拽文件到此处或 <em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 .csv、.xlsx、.xls 格式文件，文件大小不超过 5MB
            </div>
          </template>
        </el-upload>
        
        <div class="template-download">
          <el-link type="primary" :underline="true">下载导入模板</el-link>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary">导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.keyword-monitor {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.monitor-header {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
  border-radius: 8px 8px 0 0;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.add-button {
  border-radius: 20px;
  padding: 8px 20px;
  font-weight: 500;
}

.batch-actions {
  margin-right: 10px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-box {
  display: flex;
  gap: 10px;
}

.keyword-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 5px;
  flex-wrap: nowrap;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 20px;
  padding: 0 20px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-radius: 0 0 8px 8px;
}

.selection-info {
  font-size: 14px;
  color: #909399;
}

.add-category {
  display: flex;
  align-items: center;
  gap: 10px;
}

.keyword-cell {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}

.keyword-name {
  font-weight: 500;
  color: #303133;
}

.count-tag {
  font-size: 12px;
}

.sentiment-distribution {
  width: 100%;
}

.stacked-progress {
  height: 20px;
  width: 100%;
  display: flex;
  border-radius: 4px;
  overflow: hidden;
}

.stacked-segment {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.stacked-segment.positive {
  background-color: #67C23A;
}

.stacked-segment.neutral {
  background-color: #909399;
}

.stacked-segment.negative {
  background-color: #F56C6C;
}

.import-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.template-download {
  margin-top: 15px;
}
</style> 